import { createRouter, createWebHistory } from 'vue-router'

const routes = [
  {
    path: '/',
    name: 'home',
    component: () => import('../views/HomeView.vue'),
    meta: {
      requiresAuth: false,
      keepAlive: true
    }
  },
  {
    path: '/login',
    name: 'login',
    component: () => import('../views/LoginView.vue'),
    meta: {
      keepAlive: false
    }
  },
  {
    path: '/register',
    name: 'register',
    component: () => import('../views/RegisterView.vue'),
    meta: {
      keepAlive: false
    }
  },
  {
    path: '/profile',
    name: 'profile',
    component: () => import('../views/ProfileView.vue'),
    meta: {
      requiresAuth: true,
      keepAlive: true
    }
  },
  {
    path: '/messages',
    name: 'messages',
    component: () => import('../views/MessagesView.vue'),
    meta: {
      requiresAuth: true,
      keepAlive: true
    }
  },
  {
    path: '/shop',
    name: 'shop',
    component: () => import('../views/ShopView.vue'),
    meta: {
      requiresAuth: false,
      keepAlive: true
    }
  },
  {
    path: '/anime',
    name: 'anime',
    component: () => import('../views/AnimeView.vue'),
    meta: {
      requiresAuth: false,
      keepAlive: true
    }
  },
  {
    path: '/games',
    name: 'games-center',
    component: () => import('../views/GamesCenterView.vue'),
    meta: {
      requiresAuth: false,
      keepAlive: true
    }
  },
  {
    path: '/comics',
    name: 'comics',
    component: () => import('../views/ComicsView.vue'),
    meta: {
      requiresAuth: false,
      keepAlive: true
    }
  },
  {
    path: '/events',
    name: 'events',
    component: () => import('../views/EventsView.vue'),
    meta: {
      requiresAuth: false,
      keepAlive: true
    }
  }
]

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes
})

// 路由守卫，检查用户是否已登录
router.beforeEach((to, from, next) => {
  const isAuthenticated = localStorage.getItem('user') !== null
  if (to.matched.some(record => record.meta.requiresAuth) && !isAuthenticated) {
    next({ name: 'login' })
  } else {
    next()
  }
})

export default router